package cmd

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/spf13/cobra"
	"ir/core"
	"ir/core/db"
	"ir/routes"
	"ir/schedule"
	"ir/services"
	"ir/utils/xdaemon"
	"os"
)

var (
	Port   string
	daemon bool
)

var serverCmd = &cobra.Command{
	Use:     "server",
	Short:   "example:exengine server -p 8900",
	Example: "exengine server -p 8900 -d",
	Run: func(cmd *cobra.Command, args []string) {
		run()
	},
}

func init() {
	serverCmd.PersistentFlags().StringVarP(&Port, "port", "p", "8900", "监听端口号")
	serverCmd.PersistentFlags().BoolVarP(&daemon, "daemon", "d", false, "是否为守护进程模式")
}

func NewApp() (app *iris.Application, addr string) {
	cfg := core.GetConfig()
	port := cfg.GetString("port")
	addr = fmt.Sprintf(":%s", port)
	redisAddr := cfg.GetString("redis.main.Addr")
	redisAuth := cfg.GetString("redis.main.Auth")
	redisDB := cfg.GetInt("redis.main.DB")
	redisMaxIdle := cfg.GetInt("redis.main.MaxIdle")
	redisMaxOpen := cfg.GetInt("redis.main.MaxOpen")
	initRedisErr := db.InitRedis(&db.RedisConf{
		Addr:     redisAddr,
		Password: redisAuth,
		DB:       redisDB,
		MaxIdle:  redisMaxIdle,
		MaxOpen:  redisMaxOpen,
	})

	if initRedisErr != nil {
		fmt.Println("Init redis err:", initRedisErr.Error())
		os.Exit(0)
	}

	//services.Subscribe()
	go services.StartConsume()

	if daemon == true {
		logDir := core.GetLogDir()
		d := xdaemon.NewDaemon(logDir)
		d.MaxCount = 5
		d.Run()
	}

	db.DatabaseConnectionPool()

	if daemon == true {
		logDir := core.GetLogDir()
		//logDir := "logs/daemon.log"
		d := xdaemon.NewDaemon(logDir)
		d.MaxCount = 5
		d.Run()
	}

	app = iris.New()

	appLogger := logger.New(logger.Config{
		// Status displays status code
		Status: true,
		// IP displays request's remote address
		IP: true,
		// Method displays the http method
		Method: true,
		// Path displays the request path
		Path: true,
		// Query appends the url query to the Path.
		Query: true,
		// if !empty then its contents derives from `ctx.Values().Get("logger_message")
		// will be added to the logs.
		MessageContextKeys: []string{"logger_message"},
		// if !empty then its contents derives from `ctx.GetHeader("User-Agent")
		MessageHeaderKeys: []string{"User-Agent"},
	})
	app.Use(appLogger)

	routes.ApiRoutes(app)

	taskSwitch := cfg.GetInt("taskSwitch")
	if taskSwitch == 1 {
		go schedule.InitTimerTask()
	}

	return
}

func run() {
	app, addr := NewApp()
	if app != nil {
		runErr := app.Run(iris.Addr(addr), iris.WithConfiguration(iris.Configuration{
			DisableStartupLog:                 false,
			DisableInterruptHandler:           false,
			DisablePathCorrection:             false,
			EnablePathEscape:                  false,
			FireMethodNotAllowed:              false,
			DisableBodyConsumptionOnUnmarshal: false,
			DisableAutoFireStatusCode:         false,
			TimeFormat:                        "2006-01-02T15:04:05Z07:00",
			Charset:                           "UTF-8",
		}), iris.WithoutServerError(iris.ErrServerClosed))
		if runErr != nil {
			fmt.Println("App run err:", runErr.Error())
		}
	} else {
		fmt.Println("App init err")
	}
}
